import React, { useState, useEffect } from 'react';
import "./StoreManagement.scss"
import { Button, Input, Radio, Space, Table, Switch, ConfigProvider, Drawer, Form, Select, notification } from "antd"
import { DeleteFilled, SyncOutlined, FullscreenOutlined, EditOutlined, FileSearchOutlined, DeleteOutlined } from "@ant-design/icons"
import zhCN from 'antd/locale/zh_CN';
import * as service from "../../../../api"
import _ from 'lodash'
let { Search, TextArea } = Input

const StoreManagement = () => {
    const [locale] = useState(zhCN);
    let [loading, setLoading] = useState(false)
    let [data, setData] = useState([])
    // 抽屉的开关控制
    let [open, setopen] = useState(false)
    // 抽屉表单组件实例
    let [form] = Form.useForm()
    // 创建时间
    // let [createdate, setcreatedate] = useState("")
    // 判断修改或新增id
    let [stashid, setstashid] = useState({
        stashId: ""
    })
    // 当前页
    let [page, setPage] = useState(1)
    // 每页显示条数
    let [sizepage, setSizepage] = useState(4)
    let [alltotal, setalltotal] = useState()
    let onSearch = async (value: string) => {
        setLoading(true)
        // console.log("获取输入框的值：", value);
        let res = await service.default.kxd.stash_queryKey({ key: value })
        // console.log(res);
        if (res.data.code === 200) {
            setLoading(false)
            setalltotal(res.data.count)
            setData(res.data.data)
        } else if (res.data.code === 500) {
            notification.error({ message: "没有改用户名或账户" })
        }
    }
    let user_queryAll = async () => {
        setLoading(true)
        let res = await service.default.kxd.stash_queryAll({ cp: page, ps: sizepage })
        console.log("默认参数分页请求", res);
        if (res.data.code === 200) {
            setLoading(false)
            setData(res.data.data.data)
            setalltotal(res.data.count)
        }
    }
    useEffect(() => {
        let date = new Date().toLocaleString().replace(/\//g, "-")
        console.log(date);

        user_queryAll()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    let [statubtns] = useState([
        { label: '全部', value: '全部' },
        { label: '启动', value: '启动' },
        { label: '禁用', value: '禁用' },
    ])
    let renderstatus = async (e: any) => {
        // console.log("点击了：", e.target.value);
        if (e.target.value === "全部") {
            // console.log("点击了全部");
            user_queryAll()
        } else if (e.target.value === "启动") {
            console.log("点击了启动");
            setLoading(true)
            let res = await service.default.kxd.stash_queryStatus({ status: 0 })
            if (res.data.code === 200) {
                console.log(res.data.data);
                setLoading(false)
                setData(res.data.data)
                setalltotal(res.data.data.length)
            }
        } else if (e.target.value === "禁用") {
            console.log("点击了禁用");
            setLoading(true)
            let res = await service.default.kxd.stash_queryStatus({ status: 1 })
            if (res.data.code === 200) {
                console.log(res.data.data);
                setLoading(false)
                setData(res.data.data)
                setalltotal(res.data.data.length)
            }
        }
    }
    let switchstatus = async (stashId: any, stashStatus: any) => {
        // console.log(stashStatus, stashId);
        if (stashStatus === 0) {
            stashStatus = 1
            let res = await service.default.kxd.stash_updateStatus(stashId, stashStatus)
            console.log(res);

            if (res.data.code === 200) {
                notification.success({ message: "状态更改成功" })
                var newData: any = _.cloneDeep(data)
                var item: any = newData.find((item: any) => item.stashId === stashId)
                if (item) {
                    item.stashStatus = stashStatus
                }
                setData(newData)
            }
        } else if (stashStatus === 1) {
            stashStatus = 0
            let res = await service.default.kxd.stash_updateStatus(stashId, stashStatus)
            console.log(res);
            if (res.data.code === 200) {
                notification.success({ message: "状态更改成功" })
                // eslint-disable-next-line @typescript-eslint/no-redeclare
                var newData: any = _.cloneDeep(data)
                // eslint-disable-next-line @typescript-eslint/no-redeclare
                var item: any = newData.find((item: any) => item.stashId === stashId)
                if (item) {
                    item.stashStatus = stashStatus
                }
                setData(newData)
            }
        }
        // console.log("状态", stashStatus);



    }
    const columns: any = [
        {
            title: '序号',
            key: 'serialnumber',
            render: (_: any, record: any, index: any) => (
                <Space size="middle">
                    {index + 1}
                </Space>
            ),
        },
        {
            title: '仓库名称',
            dataIndex: 'stashName',
            key: 'stashName',
        },
        {
            title: '仓库编码',
            dataIndex: 'stashEncoding',
            key: 'stashEncoding',
        },
        {
            title: '状态',
            key: 'stashStatus',
            render: (_: any, record: any, index: any) => (
                <Space size="middle">
                    <Switch
                        checkedChildren="启动"
                        unCheckedChildren="禁用"
                        checked={record.stashStatus === 0 ? true : false}
                        onChange={() => { switchstatus(record.stashId, record.stashStatus) }}
                    />
                </Space>
            )
        },
        {
            title: '描述',
            key: 'stashDescription',
            dataIndex: 'stashDescription'
        },
        {
            title: '创建时间',
            key: 'stashCreateTime',
            dataIndex: 'stashCreateTime'
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: any, index: any) => (
                <Space size="middle">
                    <Button><FileSearchOutlined /></Button>
                    <Button><EditOutlined onClick={() => { onedit(record) }} /></Button>
                    <Button onClick={() => { ondel(record) }}><DeleteOutlined /></Button>
                </Space>
            ),
        },
    ];
    let ondel = async (record: any) => {
        let res = await service.default.kxd.stash_delete(record.stashId)
        if (res.data.code === 200) {
            user_queryAll()
            notification.success({ message: "删除成功" })
        }
    }
    // {
    //     "stashCreateTime": "2023-07-14T03:21:58.017Z",
    //     "stashDescription": "string",
    //     "stashEncoding": "string",
    //     "stashId": 0,
    //     "stashName": "string",
    //     "stashStatus": 0
    // }
    // 打开抽屉
    let stashadd = () => {
        setopen(true)

    }
    // 关闭抽屉
    let onClose = () => {
        setopen(false)
        form.setFieldsValue({
            stashCreateTime: "",
            stashDescription: "",
            stashEncoding: "",
            stashName: "",
            stashStatus: 0
        })
        setstashid({
            stashId: ''
        })
    }
    // 添加并且表单验证成功后的回调函数
    let onFinish = async (values: any) => {
        console.log(values);
        if (stashid.stashId) {
            let res = await service.default.kxd.stash_querySingle({ stashId: stashid.stashId })
            // console.log("请求单个数据", res);
            let newset = res.data.data
            Object.assign(newset, values)

            let setregulate = await service.default.kxd.stash_update(newset)
            // console.log("修改请求", setregulate);
            if (setregulate.data.code === 200) {
                onClose()
                user_queryAll()
                notification.success({ message: "修改成功" })
            }
        } else {
            let date = new Date().toLocaleString().replace(/\//g, "-")
            // setcreatedate(date)
            Object.assign(values, {
                stashCreateTime: date
            })
            console.log(values);
            let res = await service.default.kxd.stash_add(values)
            console.log("添加请求结果", res);
            if (res.data.code === 200) {
                onClose()
                notification.success({ message: "新增成功" })
                user_queryAll()
            } else if (res.data.code === 500) {
                onClose()
                notification.success({ message: "该角色已存在" })
            }
        }
    }
    // 选择仓库状态改变的回调
    const handleChange = (value: string) => {
        console.log(`selected ${value}`);
    }
    // 每页显示数据条数改变时显示的回调函数
    let pagechange = async (current: any, size: any) => {
        console.log("current:", current, "size:", size);
        setSizepage(size)
        setLoading(true)
        let res = await service.default.kxd.stash_queryAll({ cp: current, ps: size })
        if (res.data.code === 200) {
            setLoading(false)
            setData(res.data.data.data)
        }
    }
    // 当前页改变时的回调函数
    let onChange = async (page: any, pageSize: any) => {
        console.log("page:", page, "pageSize:", pageSize);
        setPage(page)
        setLoading(true)
        let res = await service.default.kxd.stash_queryAll({ cp: page, ps: pageSize })
        if (res.data.code === 200) {
            setLoading(false)
            setData(res.data.data.data)
        }
    }
    // 点击编辑
    let onedit = async (record: any) => {
        stashadd()
        setstashid({
            stashId: record.stashId
        })
        let res = await service.default.kxd.stash_querySingle({ stashId: record.stashId })
        if (res.data.code === 200) {
            form.setFieldsValue(res.data.data)
        }
    }
    return (
        <div className='storemanagement_box'>
            <div className="function_box">
                <div className="addbtn_box">
                    <Button type="primary" onClick={stashadd}>新增仓库</Button>
                </div>
                <Drawer title={stashid.stashId ? "修改仓库" : "新增仓库"} placement="right" onClose={onClose} open={open}>
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        onFinish={onFinish}
                        form={form}
                    >
                        <Form.Item
                            label="仓库名称"
                            name="stashName"
                            rules={[{ required: true, message: '请输入新建的仓库名' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="仓库编码"
                            name="stashEncoding"
                            rules={[{ required: true, message: '请输入新建的仓库编码' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="状态"
                            name="stashStatus"
                            rules={[{ required: true, message: '请选择状态' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                onChange={handleChange}
                                options={[
                                    { value: 0, label: '启用' },
                                    { value: 1, label: '禁用' }
                                ]}
                            />
                        </Form.Item>

                        <Form.Item
                            label="描述"
                            name="stashDescription"
                            rules={[{ required: true, message: '请描述仓库' }]}
                        >
                            <TextArea rows={4} placeholder="描述仓库" />
                        </Form.Item>
                        {/* <Form.Item
                            label="创建时间"
                            name="stashCreateTime"
                        >
                            <span>{createdate}</span>
                        </Form.Item> */}
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                {stashid.stashId ? "修改仓库" : "新增仓库"}
                            </Button>
                        </Form.Item>
                    </Form>
                </Drawer>
                <div className="btns_box">
                    <div className="status_box" >
                        <Radio.Group
                            options={statubtns}
                            onChange={renderstatus}
                            optionType="button"
                            defaultValue="全部" />
                    </div>
                    <div className="search_box">
                        <Search
                            placeholder="请输入用户名、账号关键字"
                            allowClear
                            enterButton="搜索"
                            size="middle"
                            onSearch={onSearch}
                        />
                    </div>
                    <div className="iocnbtns">
                        <div className="del">
                            <DeleteFilled />
                        </div>
                        <div className="reset">
                            <SyncOutlined />
                        </div>
                        <div className="fullscreen">
                            <FullscreenOutlined />
                        </div>
                    </div>
                </div>
            </div>
            <div className="table_box">
                <ConfigProvider locale={locale}>
                    <Table
                        columns={columns}
                        dataSource={data}
                        size="middle"
                        loading={loading}
                        pagination={
                            {
                                position: ["bottomCenter"],
                                pageSize: sizepage, // 每页显示数据条数
                                current: page, // 当前页
                                showQuickJumper: true, //快速跳转
                                total: alltotal, // 所有条数
                                showTotal: (total: any) => `共 ${total} 条数据`,
                                pageSizeOptions: [2, 4, 6, 8, 10],
                                onShowSizeChange: pagechange,
                                onChange: onChange,
                                showSizeChanger: true
                            }
                        }
                    />
                </ConfigProvider>
            </div>
        </div>
    );
};

export default StoreManagement;